package com.teamsuperfitness.apps.client.presenters;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SelectionModel;
import com.teamsuperfitness.apps.client.service.ContractService;
import com.teamsuperfitness.apps.client.service.ContractServiceAsync;
import com.teamsuperfitness.apps.shared.events.ContractReqListUpdateEvent;
import com.teamsuperfitness.apps.shared.events.ContractReqListUpdateEventHandler;
import com.teamsuperfitness.apps.shared.events.ContractSelectedEvent;
import com.teamsuperfitness.apps.shared.model.Contract;

public class ContractListPresenter implements IPresenter {
    private final Display display;
    private final SimpleEventBus eventBus;
    private final ContractServiceAsync service = GWT.create(ContractService.class); 
    
    public interface Display {
        void setData(List<Contract> data);
        Widget asWidget();
        SelectionModel<Contract> getContractSelector();
        Contract getSelected();
    }

    public ContractListPresenter(SimpleEventBus eventBus, Display view) {
        this.eventBus = eventBus;
        this.display = view;
        bind();
    }
    
    public void go(HasWidgets container) {
        container.clear();
        container.add(this.display.asWidget());
    }
    
    public void bind() {
        eventBus.addHandler(ContractReqListUpdateEvent.TYPE, new ContractReqListUpdateEventHandler() {
            public void onContractReqUpdate(ContractReqListUpdateEvent event) {
                service.getAll(new AsyncCallback<List<Contract>>() {
                    public void onFailure(Throwable caught) {}
                    public void onSuccess(List<Contract> result) {
                        display.setData(result);
                    }});
            }
        });
        display.getContractSelector().addSelectionChangeHandler(new Handler() {
            public void onSelectionChange(SelectionChangeEvent event) {
                eventBus.fireEvent(new ContractSelectedEvent(display.getSelected()));
            }
        });
    }

}
